package com.yueya.common.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.jfinal.aop.Clear;
import com.jfinal.aop.Duang;
import com.jfinal.core.Controller;
import com.jfinal.kit.FileKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.wj.kit.ImageUploadKit;
import com.yueya.basic.dict.model.Dict;
import com.yueya.basic.user.model.User;
import com.yueya.basic.user.service.UserService;
import com.yueya.common.constant.BaseConstant;
import com.yueya.common.util.DateUtil;
import com.yueya.common.util.UUIDGenerator;
import com.yueya.common.util.UploadUtil;

/**
 * CommonController
 */

public class CommonController extends Controller {

	UserService service = Duang.duang(UserService.class);

	public void index() {
		String cookieLoginName = this.getCookie(BaseConstant.COOKIE_KEY_LOGINNAME);
		this.setAttr("cookieLoginName", cookieLoginName);
		render("/WEB-INF/views/basic/login/login.jsp");
	}

	/**
	 * 登录跳转
	 */
	@Clear
	public void login() {
		String userName = this.getPara("usernm");
		String passwd = this.getPara("passwd");

		User user = service.authentication(userName, passwd);
		if (user != null) {
			// 添加登陆名到cookie
			int age = 365 * 24 * 60 * 60;
			this.setCookie(BaseConstant.COOKIE_KEY_LOGINNAME, userName, age);
			this.setCookie("userid", user.getStr("id"), age);

			// 更新用户的最后登陆时间
			user.set("last_login_time", DateUtil.getDate(DateUtil.timeFormat));
			user.update();

			this.redirect("/main");
		} else {
			this.setAttr("msg", "请正确输入用户名与密码.");
			this.render("/WEB-INF/views/basic/login/login.jsp");
		}

	}

	/**
	 * 注销
	 */
	public void loginOut() {
		removeCookie(BaseConstant.COOKIE_KEY_LOGINNAME);
		render("/WEB-INF/views/basic/login/login.jsp");
	}

	/**
	 * 导入
	 */
	public void importList() {
		render("/WEB-INF/views/basic/poi/import_list.jsp");
	}

	public void importView() {
		this.keepPara("type");
		render("/WEB-INF/views/basic/poi/import_view.jsp");
	}

	@Clear()
	public void checkUser() {
		String userName = this.getPara("usernm");
		Record r = User.dao.getUserByLoginName(userName);
		if (r != null) {
			renderText("true");
		} else {
			renderText("false");
		}
	}

	// 上传logo文件
	@SuppressWarnings("rawtypes")
	public void upload() {
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		String savePath = "";
		String saveUrl = "";
		try {
			List items = upload.parseRequest(this.getRequest());
			if (null != items) {
				Iterator itr = items.iterator();
				while (itr.hasNext()) {
					FileItem item = (FileItem) itr.next();
					if (item.isFormField()) {
						continue;
					} else {

						// 检查目录
						File uploadDir = new File(savePath);
						if (!uploadDir.isDirectory()) {

							return;
						}
						// 检查目录写权限
						if (!uploadDir.canWrite()) {

							return;
						}

						String dirName = this.getPara("dir");
						if (dirName == null) {
							dirName = "photo";
						}

						// 创建文件夹
						savePath += dirName + "/";
						saveUrl += dirName + "/";
						File saveDirFile = new File(savePath);
						if (!saveDirFile.exists()) {
							saveDirFile.mkdirs();
						}
						SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
						String ymd = sdf.format(new Date());
						savePath += ymd + "/";
						saveUrl += ymd + "/";
						File dirFile = new File(savePath);
						if (!dirFile.exists()) {
							dirFile.mkdirs();
						}

						String fileName = UploadUtil.generateFileName(item.getName());
						File savedFile = new File(savePath, fileName);
						item.write(savedFile);
						saveUrl += fileName;
						System.out.println(saveUrl);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		renderText(saveUrl);
	}

	@Clear
	public void initDict() {
		String[] goodsTypes = new String[] { "普货", "重货", "泡货", "设备", "配件", "百货", "建材", "食品", "饮料", "化工", "农药", "水果",
				"蔬菜", "木材", "煤炭", "石材", "瓷砖", "其他" };
		Dict d = null;
		for (int i = 0; i < goodsTypes.length; i++) {
			d = new Dict();
			d.set("id", UUIDGenerator.getUUID());
			d.set("category", "goods_type");
			d.set("name", goodsTypes[i]);
			d.set("value", i);
			// d.save();
		}

		String[] trurkkLengths = new String[] { "4.2米", "4.5米", "6.2米", "6.8米", "7.2米", "8.2米", "8.6米", "9.6米", "11.7米",
				"12.5米", "13米", "13.5米", "14米", "17米", "17.5米", "18米", "4.2-9.6米", "11.7-13.5米", "14-17米" };
		for (int i = 0; i < trurkkLengths.length; i++) {
			d = new Dict();
			d.set("id", UUIDGenerator.getUUID());
			d.set("category", "truck_length");
			d.set("name", trurkkLengths[i]);
			d.set("value", trurkkLengths[i].replaceAll("米", ""));
			// d.save();
		}

		String[] truckRequire = new String[] { "小货", "单桥", "后八轮", "双桥", "前四后四", "前四后六", "前四后八", "前四后十", "五桥", "六桥",
				"半挂", "一拖二", "一拖三", "二拖二", "二拖三", "冷藏", "保温", "危货", "油罐", "自卸", "工程", "特种拖" };
		for (int i = 0; i < truckRequire.length; i++) {
			d = new Dict();
			d.set("id", UUIDGenerator.getUUID());
			d.set("category", "truck_require");
			d.set("name", truckRequire[i]);
			d.set("value", i);
			// d.save();
		}

		String[] loadRequire = new String[] { "平板", "高栏", "高低板", "箱式", "保温", "冷藏", "危险品" };
		for (int i = 0; i < loadRequire.length; i++) {
			d = new Dict();
			d.set("id", UUIDGenerator.getUUID());
			d.set("category", "load_require");
			d.set("name", loadRequire[i]);
			d.set("value", i);
			d.save();
		}
	}

	public void QnUpload() {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> error = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();

		UploadFile uf = getFile("file");
		if (null != uf && null != uf.getFile() && uf.getFile().exists()) {
			String key = UUIDGenerator.getUUID();
			String filePath;
			boolean bl = false;
			try {
				filePath = uf.getFile().getCanonicalPath();
				bl = ImageUploadKit.uplaod(filePath, key);
			} catch (IOException e) {
				e.printStackTrace();

				map.put("result", false);
				error.put("errcode", "WJ.UPLOAD_FAIL");
				error.put("errmsg", "上传失败");
				map.put("error", error);

				FileKit.delete(uf.getFile());
				renderJson(map);
			}
			if (bl) {
				map.put("result", true);
				data.put("key", key);
				data.put("url", ImageUploadKit.getImage(key));
				map.put("data", data);
				map.put("msg", "上传成功");
			} else {
				map.put("result", false);
				error.put("errcode", "WJ.UPLOAD_FAIL");
				error.put("errmsg", "上传失败");
				map.put("error", error);
			}
		} else {
			map.put("result", false);
			error.put("errcode", "WJ.UPLOAD_FAIL");
			error.put("errmsg", "上传失败");
			map.put("error", error);
		}
		FileKit.delete(uf.getFile());
		renderJson(map);
	}
}